#define _CRT_SECURE_NO_WARNINGS
#include"SLIST.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
// 动态申请一个节点
SLNode* BuySListNode(SLDataType x)
{
	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
// 单链表打印
void SListPrint(SLNode* plist)
{
	    assert(plist);
		printf("%d ", plist->data);
		while (plist->next != NULL)
		{
			plist = plist->next;
			printf("%d ", plist->data);
		}
	}
// 单链表尾插
void SListPushBack(SLNode** pplist, SLDataType x)
{
	SLNode* next = BuySListNode(x);
	//链表为空
	if (*pplist == NULL)
	{
		*pplist = next;
	}
	//链表不为空
	else
	{
		SLNode* tail = *pplist;
		//找到尾节点
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = next;
	}
}
// 单链表的头插
void SListPushFront(SLNode** pplist, SLDataType x)
{
	SLNode* pcur = *pplist;
	SLNode* head = BuySListNode(x);
	head->next =pcur;
	*pplist = head;
}
// 单链表的尾删
void SListPopBack(SLNode** pplist)
{
	assert(*pplist);
	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{

		SLNode* tail = *pplist;
		//找到尾节点的前一个结点
		while (tail->next->next!= NULL)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}
// 单链表头删
void SListPopFront(SLNode** pplist)
{
	assert(*pplist);
	SLNode* head = *pplist;
	*pplist = head->next;
	free(head);
	head = NULL;
}
// 单链表查找
SLNode* SListFind(SLNode* plist, SLDataType x)
{
	SLNode* pcur =plist;
	while (pcur!= NULL)
	{
		if (pcur->data == x)return pcur;
		else pcur = pcur->next;
	}
	return NULL;
}
// 单链表在pos位置之后插入x
// 分析思考为什么不在pos位置之前插入？
void SListInsertAfter(SLNode* pos, SLDataType x)
{
	assert(pos);
	SLNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
// 单链表删除pos位置之后的值
// 分析思考为什么不删除pos位置？
void SListEraseAfter(SLNode* pos)
{
	assert(pos);
	SLNode* next = pos->next->next;
	free(pos->next);
	pos->next = next;
}

// 在pos的前面插入
void SLTInsert(SLNode** pphead, SLNode* pos, SLDataType x)
{
	assert(pos);
	//pos为链表首元素
	SLNode* newnode = BuySListNode(x);
	SLNode* pcur = *pphead;
	if (pcur == pos)
	{
		newnode->next = pos;
		*pphead = newnode;
	}
	else
	{
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		pcur->next = newnode;
		newnode->next = pos;
	}
}
// 删除pos位置
void SLTErase(SLNode** pphead, SLNode* pos)
{
	SLNode* pcur = *pphead;
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		pcur->next = pos->next;
		free(pos);
		pos = NULL;
}
void SLTDestroy(SLNode** pphead)
{
	assert(pphead&&*pphead);
	SLNode*pcur=*pphead;
    while(pcur)
    {
        SLNode*next=pcur->next;
        free(pcur);
        pcur=next;
    }
    *pphead=NULL;
}